package com.vf.admin.client.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dto.*;
import com.vf.admin.client.service.*;
import com.vf.admin.client.service.impl.ZhidingServiceImpl;
import com.vf.admin.client.tx.utils.TxIm;
import com.vf.admin.common.Constants;
import com.vf.admin.common.annotation.RedisSynchronized;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.fiwork.util.DateUtils;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.miaodong.service.AfterUserService;
import com.vf.admin.utils.AgeUtils;
import com.vf.admin.utils.DistanceUtils;
import com.vf.admin.utils.StringEx;
import com.vf.admin.utils.TimeUtils;
import lombok.SneakyThrows;
import org.apache.hadoop.mapred.IFile;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.vf.admin.client.common.ClientConstants.client_toke;
import static com.vf.admin.client.tx.utils.TLSSigAPIv2.genUserSig;
import static com.vf.admin.common.Constants.*;
import static com.vf.admin.utils.DateJisuan.format;
import static com.vf.admin.utils.StringEx.isNull;
import static com.vf.admin.utils.ConstellationUtil.*;

/**
 * @author anxiang
 * @version 1.0.0
 * @ClassName AppUserController.java
 * @Description TODO 用户
 * @createTime 2021年07月21日 10:58:00
 */
@CrossOrigin
@Controller
@RequestMapping("/app/user")
public class AppUserController extends ClientBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppDynamicService appDynamicService;
    @Autowired
    AppUserDressupService appUserDressupService;
    @Autowired
    AppUserGiftService appUserGiftService;
    @Autowired
    private AppGiftService appGiftService;
    @Autowired
    AppDynamicDianzanService appDynamicDianzanService;
    @Autowired
    AppFollowService appFollowService;
    @Autowired
    AppUserDongtaiService appUserDongtaiService;
    @Autowired
    AppUserLaHeiService appUserLaHeiService;
    @Autowired
    AppRoomLaHeiService appRoomLaHeiService;
    @Autowired
    AppRoomJinyanService appRoomJinyanService;
    @Autowired
    AppRoomAdminService appRoomAdminService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppRoomService appRoomService;
    @Autowired
    AppZhiyeFuService appZhiyeFuService;
    @Autowired
    AppZhiyeService appZhiyeService;
    @Autowired
    AppBiaoqianService appBiaoqianService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    private AppMingXiShouLiService appMingXiShouLiService;
    @Autowired
    private AppPriceSetService priceSetService;
    @Autowired
    private AppVisitorService visitorService;
    @Autowired
    private AppMingXiZuanShiService mingXiZuanShiService;
    @Autowired
    private AppMingxiJinbiService mingxiJinbiService;
    @Autowired
    private AppSignatureParseLogService appSignatureParseLogService;
    @Autowired
    private AppAuthUserService appAuthUserService;
    @Autowired
    private AppIntimacyGuardService appIntimacyGuardService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private AppInvitationRecordService appInvitationRecordService;
    @Autowired
    private AppSetSameCityService appSetSameCityService;
    @Autowired
    private PopupLogService popupLogService;
    @Autowired
    private AppGuardService appGuardService;
    @Autowired
    private ZhidingServiceImpl zhidingService;
    @Autowired
    private MessageChatFromService messageChatFromService;
    @Autowired
    private LovelyGodLogService lovelyGodLogService;
    @Autowired
    private AppGiftService giftService;
    @Autowired
    private AppUserSettingService appUserSettingService;
    @Autowired
    private SystemAlertService systemAlertService;
    @Autowired
    private AppHeadwearService headwearService;
    @Autowired
    private AppSsProvincesService provincesService;
    @Autowired
    AfterUserService afterUserService;

    /**
     * 内部使用
     */
    @RequestMapping(value = "/getUserInfoSearch")
    @ResponseBody
    public Result getUserInfoSearch(String loginNames) {

        if (ObjectUtil.isNotEmpty(loginNames)){
            List<AppUser> userInfoSearch = appUserService.getUserInfoSearch(loginNames);
            return this.sucessJSON(userInfoSearch);
        }


        return this.errorJSON("参数不正确");

    }







    /**
     * 是否数据号  时间查询  男女
     *
     * @return
     */
    @GetMapping(value = "/getUserInfoPage")
    @ResponseBody
    public Result getUserInfoPage(SplitPageBean splitPage, String startDate, String endDate, Integer sex, Integer isReal) {
        Map<String, Object> map = new HashMap<>();
        map.put("isReal", isReal);//
        map.put("sex", sex);//
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        long start = System.currentTimeMillis();
        List<AppUser> list = appUserService.findList(map, splitPage);
        return this.sucessJSON(list);

    }

    /**
     * 是否数据号  时间查询  男女
     *
     * @return
     */
    @GetMapping(value = "/getUnReadUserPage")
    @ResponseBody
    public Result getUnReadUserPage(SplitPageBean splitPage, Integer sex, Integer isReal) {
        Map<String, Object> map = new HashMap<>();
        map.put("isReal", isReal);
        map.put("sex", sex);
        long start = System.currentTimeMillis();
        List<AppUnReadUser> list = appUserService.findUnReadList(map, splitPage);
        for (AppUnReadUser user: list) {
            int count = getUnReadCount(user.getTengxuncode());
            user.setUnReadCount(count);
        }
        System.out.println(System.currentTimeMillis() - start);
        list.sort((num1,num2)->{return num2.getUnReadCount().compareTo(num1.getUnReadCount());});

        return this.sucessJSON(list);

    }

    @Async
    public int getUnReadCount(int txcode) {
        String userSig = genUserSig("admin", 3600 * 24 * 7);
        String url = "https://console.tim.qq.com/v4/openim/get_c2c_unread_msg_num?sdkappid=1400800054&identifier=admin&usersig=" + userSig + "&random=2706793671&contenttype=json";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("To_Account", ""+txcode);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        StringEntity params = new StringEntity(jsonObject.toJSONString(), "utf-8");
        params.setContentType("application/json");
        httpPost.setEntity(params);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String strResult = EntityUtils.toString(response.getEntity(), "utf-8");
            org.json.JSONObject object = new org.json.JSONObject(strResult);
            return object.getInt("AllC2CUnreadMsgNum");
        } catch (IOException e) {
            return 0;
        }
    }


    /**
     * 获取用户信息
     */
    @PostMapping(value = "/getUserInfo")
    @ResponseBody
    public Result getUserInfo(@RequestBody GetUserInfoParam param) {
        String key = "1e55dbf412cb74d5e2c21fb6452408c7";
        if (ObjectUtil.isNotEmpty(param.getKeys()) && ObjectUtil.isNotEmpty(param.getTengxuncode())) {
            if (param.getKeys().equals(key)) {
                //用户信息转移Dto
                GetUserInfoDto ud = new GetUserInfoDto();
                //查询用户
                AppUser userInfo = appUserService.getUserInfo(param.getId(), param.getLoginname(), param.getTengxuncode());
                BeanUtils.copyProperties(userInfo, ud);
                //电话
                ud.setPhoneNum(userInfo.getLoginname());
                //性别
                if (ObjectUtil.isNotEmpty(userInfo.getSex())) {
                    if (userInfo.getSex().equals(1)) {
                        ud.setSexString("男");
                    }
                    if (userInfo.getSex().equals(2)) {
                        ud.setSexString("女");
                    }
                } else {
                    ud.setSexString("未设置");
                }
                //在线状态
                if (ObjectUtil.isNotEmpty(userInfo.getOnlinestatus())) {
                    if (userInfo.getOnlinestatus().equals(1)) {
                        ud.setOnlinestatusString("在线");
                    }
                    if (userInfo.getOnlinestatus().equals(2)) {
                        ud.setOnlinestatusString("不在线");
                    }
                } else {
                    ud.setOnlinestatusString("未获取到在线状态");
                }
                //钻石
                if (ObjectUtil.isEmpty(userInfo.getDiamonds())) {
                    ud.setDiamonds("0");
                } else {
                    ud.setDiamonds(userInfo.getDiamonds().toString());
                }
                //金币
                if (ObjectUtil.isEmpty(userInfo.getJinbi())) {
                    ud.setJinbi("0");
                } else {
                    ud.setJinbi(userInfo.getJinbi().toString());
                }
                //会员
                if (ObjectUtil.isNotEmpty(userInfo.getVipEndDate())) {
                    ud.setIsVip("vip");
                } else {
                    ud.setIsVip("非vip");
                }
                //详细地址
                if (ObjectUtil.isNotEmpty(userInfo.getAddressdetail())) {
                    ud.setAddressdetail(userInfo.getAddressdetail());
                } else {
                    ud.setAddressdetail(userInfo.getAddress());
                }
                //身高
                if (ObjectUtil.isEmpty(userInfo.getShengao())) {
                    ud.setShengao("无数据");
                } else {
                    ud.setShengao(String.valueOf(userInfo.getShengao()));
                }
                //体重
                if (ObjectUtil.isEmpty(userInfo.getTizhong())) {
                    ud.setTizhong("无数据");
                } else {
                    ud.setTizhong(String.valueOf(userInfo.getTizhong()));
                }
                //年龄
                if (ObjectUtil.isEmpty(userInfo.getAge())) {
                    ud.setAge("无数据");
                } else {
                    ud.setAge(String.valueOf(userInfo.getAge()));
                }
                //职业
                if (ObjectUtil.isEmpty(userInfo.getZhiyename())) {
                    ud.setWorker("无数据");
                } else {
                    ud.setWorker(userInfo.getZhiyename());
                }
                return this.sucessJSON(ud);
            }
            return this.errorJSON("请联系管理员取得正确访问密钥");
        }

        return this.errorJSON("参数不正确");

    }

    /**
     * 获取用户信息
     */
    @RequestMapping(value = "/getUserInfoApp")
    @ResponseBody
    public Result getUserInfoApp(Integer id) {

        //用户信息转移Dto
        GetUserInfoDto ud = new GetUserInfoDto();
        //查询用户
        AppUser userInfo = appUserService.getUserInfo(id, null, null);
        BeanUtils.copyProperties(userInfo, ud);
        //电话
        ud.setPhoneNum(userInfo.getLoginname());
        //性别
        if (ObjectUtil.isNotEmpty(userInfo.getSex())) {
            if (userInfo.getSex().equals(1)) {
                ud.setSexString("男");
            }
            if (userInfo.getSex().equals(2)) {
                ud.setSexString("女");
            }
        } else {
            ud.setSexString("未设置");
        }
        //在线状态
        if (ObjectUtil.isNotEmpty(userInfo.getOnlinestatus())) {
            if (userInfo.getOnlinestatus().equals(1)) {
                ud.setOnlinestatusString("在线");
            }
            if (userInfo.getOnlinestatus().equals(2)) {
                ud.setOnlinestatusString("不在线");
            }
        } else {
            ud.setOnlinestatusString("未获取到在线状态");
        }
        //钻石
        if (ObjectUtil.isEmpty(userInfo.getDiamonds())) {
            ud.setDiamonds("0");
        } else {
            ud.setDiamonds(userInfo.getDiamonds().toString());
        }
        //金币
        if (ObjectUtil.isEmpty(userInfo.getJinbi())) {
            ud.setJinbi("0");
        } else {
            ud.setJinbi(userInfo.getJinbi().toString());
        }
        //会员
        if (ObjectUtil.isNotEmpty(userInfo.getVipEndDate())) {
            ud.setIsVip("vip");
        } else {
            ud.setIsVip("非vip");
        }
        //详细地址
        if (ObjectUtil.isNotEmpty(userInfo.getAddressdetail())) {
            ud.setAddressdetail(userInfo.getAddressdetail());
        } else {
            ud.setAddressdetail(userInfo.getAddress());


        }
        return this.sucessJSON(ud);

    }

    /**
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 获取用户最新的信息
     */
    @RequestMapping(value = "/getUinfo", method = RequestMethod.POST)
    @ResponseBody
    public Result getUinfo(HttpServletRequest request) {
        try {
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //用户信息转移Dto
            UserDto ud = new UserDto();
            BeanUtils.copyProperties(user, ud);
            //生日格式转换
            ud.setBirthday(removeSfm(user.getBirthday()));
            //判断形象墙 是否存在
            if (!isNull(ud.getXingxiang())) {
                String[] arr = ud.getXingxiang().split(","); //形象墙存在 切割
                if (arr.length > 0) {
                    //移入数组
                    ud.setXingxiangList(Arrays.asList(arr));
                }
            }
            //判断用户是否是贵族
            if (user.getIsguizu() == 1) {
                //是贵族
                //根据贵族id  获取贵族图标
                String medal = guizuCacheMap.get(user.getNobleid());
                ud.setMedal(medal);
            } else {
                ud.setMedal("");
            }
            //判断是否能发图片消息
            AppSetup setup = appSetupService.get();
            if (user.getChongzhimoney() >= setup.getImgmoney() || user.getSex().equals(SEX_STATE_NV)) {
                ud.setIssendimg(1);
            } else {
                ud.setIssendimg(2);
            }
            ud.setMinimgmoney("累计充值金额满" + setup.getImgmoney() + "元,方可无限制发送图片消息");
            //批量fa布人默认头饰
            AppUserDressup userDressups = appUserDressupService.getUserid(user.getId(), 2);
            //判断是否设置过头饰
            if (!StringUtils.isEmpty(userDressups)) {
                //存在则放入
                ud.setToushi(Constants.toushiCacheMap.get(userDressups.getMountsid()));
            } else {
                //不存在
                ud.setToushi("");
            }

            //语音签名内容 时长 点赞数 是否点赞
            VoiceSignatureDto signatureDto = appAuthUserService.infoVoiceSignature(userId, userId);
            ud.setSignatureDto(signatureDto);
            //土豪值
            /*double jinbiGrowthSum = mingxiJinbiService.jinbiGrowthSum(userId);
            ud.setMoneyValue(jinbiGrowthSum);*/
            //认证信息
            List<UserAuthDto> userAuthDtoList = appAuthUserService.infoByUser(userId);
            ud.setUserAuthDtoList(userAuthDtoList);

            Integer isReal = appAuthUserService.infoByUserAndName(userId, ClientConstants.UserAuth.REAL_AUTH);
            ud.setIsReal(isReal);

            int visitorCount = visitorService.visitorCount(userId);
            ud.setVisitorCount(visitorCount);

            Map<String, Object> vipMap = appUserService.isVipMap(userId);
            ud.setVipMap(vipMap);
            return this.sucessJSON(ud);
        } catch (Exception e) {
            logger.error("获取用户最新的信息异常:", e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 获取用户上一次进入的房间腾讯code
     */
    @RequestMapping(value = "/getUlastRoom", method = RequestMethod.POST)
    @ResponseBody
    public Result getUlastRoom(HttpServletRequest request) {
        try {
            Map<String, Object> toMap = new HashMap<>(16);
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            toMap.put("roomTxCode", user.getLastroomtxcode());
            return this.sucessJSON(toMap);
        } catch (Exception e) {
            logger.error("获取用户上一次进入的房间腾讯code异常:", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }

    int i = 0;

    /**
     * 查询其他用户的个人信息
     *
     * @param userid 用户id
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 查看某个用户的信息
     */
    @RequestMapping(value = "/lookTinfo")
    @ResponseBody
    public Result lookTinfo(HttpServletRequest request, Integer userid, @RequestParam(value = "lon", required = false) Double lon, @RequestParam(value = "lat", required = false) Double lat) {
        try {
            long time0 = System.currentTimeMillis();
            if (isNull(userid)) {
                return errorJSON("ID不能为空");
            }
            //根据userid获取最新数据
            AppUser user = appUserService.getTcOrId(userid);
            long time1 = System.currentTimeMillis();
            System.out.println("查看用户信息1111-----"+ (time1-time0));
            if (StringUtils.isEmpty(user)) {
                return errorJSON("用户不存在");
            }
            //用户信息转移Dto
            ToUserDto ud = new ToUserDto();
            BeanUtils.copyProperties(user, ud);
            //
            if (ObjectUtil.isEmpty(user.getWeChatNum())) {
                ud.setWeChatNum("");
            }
            if (ObjectUtil.isEmpty(user.getQqNum())) {
                ud.setQqNum("");
            }
            if (ObjectUtil.isEmpty(user.getPhoneNum())) {
                ud.setPhoneNum("");
            }

            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser appUser1 = appUserService.get(userId);
            AppFollow follow = appFollowService.getFollew(appUser1.getId(), user.getId());
            long time2 = System.currentTimeMillis();
            System.out.println("查看用户信息22222-----"+ (time2-time1));
            if (!StringUtils.isEmpty(follow)) {
                //已关注
                ud.setGuanzhuState(1);
            } else {
                //未查询到记录  未关注
                ud.setGuanzhuState(2);
            }
            List<String> bqList = new ArrayList<>();
            //判断用户是否添加标签
            if (!isNull(ud.getBiaoqianname())) {
                //切割
                String[] bq = ud.getBiaoqianname().split(",");
                bqList = Arrays.asList(bq);
            }
            ud.setBiaoqianList(bqList);
            //是否开启 不看ta动态
            AppUserDongtai dongtai = appUserDongtaiService.getByUseridAndGbUserid(appUser1.getId(), user.getId());
            long time3 = System.currentTimeMillis();
            System.out.println("查看用户信息33333-----"+ (time3-time2));
            if (StringUtils.isEmpty(dongtai)) {
                ud.setNotDongtaiState(2);
            } else {
                ud.setNotDongtaiState(1);
            }
            //获取是否已经拉黑
            AppUserLaHei appUserLaHei = appUserLaHeiService.getByUseridAndLhUserid(appUser1.getId(), user.getId());
            long time4 = System.currentTimeMillis();
            System.out.println("查看用户信息44444-----"+ (time4-time3));
            if (StringUtils.isEmpty(appUserLaHei)) {
                ud.setIslahei(2);
            } else {
                //有记录   已啦黑
                ud.setIslahei(1);
            }
            //获取粉丝数
            Map<String, Object> mapOne = new HashMap<>();
            mapOne.put("userid", user.getId());
            List<AppFollow> one = appFollowService.findByListAll(mapOne);
            ud.setFansnumall(one.size());
            long time5 = System.currentTimeMillis();
            System.out.println("查看用户信息555-----"+ (time5-time4));
            //获取关注数
            Map<String, Object> mapTwo = new HashMap<>();
            mapTwo.put("followeduserid", user.getId());
            List<AppFollow> listOne = appFollowService.findByListAll(mapTwo);
            ud.setGuanzhu(listOne.size());
            //获取礼物数
            List<AppMingXiShouLi> appMingXiShouLis = appMingXiShouLiService.selectList(user.getId());
            long time6 = System.currentTimeMillis();
            System.out.println("查看用户信息6666-----"+ (time6-time5));
            Integer sum = appMingXiShouLis.stream().collect(Collectors.summingInt(AppMingXiShouLi::getLiwunum));
            ud.setGiftNumber(sum);

            //语音签名内容 时长 点赞数 是否点赞
            VoiceSignatureDto signatureDto = appAuthUserService.infoVoiceSignature(userId, user.getId());
            long time7 = System.currentTimeMillis();
            System.out.println("查看用户信息7777-----"+ (time7-time6));
            ud.setSignatureDto(signatureDto);
            //认证信息-----
            List<UserAuthDto> userAuthDtoList = appAuthUserService.infoByUser(user.getId());
            ud.setUserAuthDtoList(userAuthDtoList);
            long time8 = System.currentTimeMillis();
            System.out.println("查看用户信息8888-----"+ (time8-time7));//慢查询


            Integer isReal = appAuthUserService.getReal(user.getId(), ClientConstants.UserAuth.REAL_AUTH);
            ud.setIsReal(isReal);
            long time9 = System.currentTimeMillis();
            System.out.println("查看用户信息9999-----"+ (time9-time8));

            Map<Integer, Integer> toushiMap = new HashMap<>(16);
            List<AppUserDressup> userDressups = appUserDressupService.getPiliang(String.valueOf(user.getId()), 2);
            for (AppUserDressup userDressup : userDressups) {
                if (userDressup.getState() == 1) {
                    toushiMap.put(userDressup.getUserid(), userDressup.getMountsid());
                }
            }
            long time10= System.currentTimeMillis();
            System.out.println("查看用户信息1010-----"+ (time10-time9));

            if (appUser1.getId().compareTo(user.getId()) != 0) {
                visitorLog(appUser1, user);
            }

            int visitorCount = visitorService.visitorCount(user.getId());
            ud.setVisitorCount(visitorCount);
            ud.setCharmvalue(user.getCharmvalue());
            ud.setAge(AgeUtils.getAgeByBirth(user.getBirthday()));
            long time11 = System.currentTimeMillis();
            System.out.println("查看用户信息1111-----"+ (time11-time10));//慢查询

            //用户个人设置
            Map<String, Object> userSetting = appUserSettingService.get(user.getId());
            ud.setUserSetting(userSetting);
            long time12 = System.currentTimeMillis();
            System.out.println("查看用户信息1212-----"+ (time12-time11));
            //vip
            Map<String, Object> vipMap = appUserService.isVipMap(user.getId());
            ud.setVipMap(vipMap);

            //位置信息
            Integer hiddenArea = 0;
            if (ObjectUtil.isNotNull(userSetting) && ObjectUtil.isNotNull(userSetting.get("hiddenArea"))) {
                hiddenArea = Integer.valueOf(userSetting.get("hiddenArea").toString());
            }
            ud.setRegion("未知");
            if (hiddenArea == 1 && lon != null && lat != null && !StringUtils.isEmpty(user.getLon()) && !StringUtils.isEmpty(user.getLat())) {
                double distance = DistanceUtils.getDistance(lon, lat, Double.valueOf(user.getLon()), Double.valueOf(user.getLat()));
                ud.setRegion(distance + "km");
            } else if (hiddenArea == 2) {
                if (user.getShiid() != null) {
                    SsProvinces ssProvinces = provincesService.get(user.getShiid());
                    ud.setRegion(ssProvinces.getProvince());
                }
            }
            long time13 = System.currentTimeMillis();
            System.out.println("查看用户信息1313-----"+ (time13-time12));

            System.out.println("查看用户信息-----"+ (System.currentTimeMillis()-time0));
            return this.sucessJSON(ud);
        } catch (Exception e) {
            logger.error("查看某个用户的信息异常:", e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 保存访问和被访问记录
     *
     * @param from
     * @param to
     */
    private void visitorLog(AppUser from, AppUser to) {

        if (from.getId() != to.getId()) {
            AppVisitor appVisitor = visitorService.findByVisitorLog(from.getId(), to.getId());
            if (appVisitor != null) {
                appVisitor.setGusttime(new Date());
                visitorService.save(appVisitor);
            } else {
                AppVisitor visitor = new AppVisitor();
                visitor.setGustid(from.getId());
                visitor.setGustname(from.getNick());
                visitor.setGustpic(from.getPic());
                visitor.setGustphone(from.getLoginname());
                visitor.setUserid(to.getId());
                visitor.setPic(to.getPic());
                visitor.setNick(to.getNick());
                visitor.setPhone(to.getLoginname());
                visitor.setGusttime(new Date());
                visitor.setGustsex(from.getSex());
                visitorService.save(visitor);
            }
            //双方没有聊天关系，并且今天没有发送过系统通知
            MessageChatFrom messageChatFrom = messageChatFromService.get(from.getId(), to.getId());
            if (messageChatFrom == null) {
                String key = String.format(RedisKeys.LOOK_ALERT, from.getId(), to.getId());
                if (!redisUtil.hasKey(key)) {
                    systemAlertService.sendML_LOOK_T_INFO(to.getTengxuncode(), from.getNick());
                    redisUtil.set(key, "1", DateUtils.calculateCurrentTime2SecondDaySec());
                }
            }
        }
    }

    /**
     * @param txcode 腾讯code
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 根据腾讯code查看某个用户的信息
     */
    @RequestMapping(value = "/txCodelookTinfo", method = RequestMethod.POST)
    @ResponseBody
    public Result txCodelookTinfo(HttpServletRequest request, Integer txcode, Integer roomid) {
        try {
            if (isNull(txcode)) {
                return errorJSON("txcode不能为空");
            }
            if (isNull(roomid)) {
                return errorJSON("roomid不能为空");
            }
            //根据userid获取最新数据
            AppUser user = appUserService.getTengxuncodeByUser(txcode);
            //判断用户是否存在
            if (user == null || user.getId() == null || user.getId() <= 0) {
                return errorJSON("用户不存在");
            }
            AppRoom room = appRoomService.getById(roomid);
            if (StringUtils.isEmpty(room)) {
                return errorJSON("房间不存在");
            }
            //用户信息转移Dto
            ToUserDto ud = new ToUserDto();
            BeanUtils.copyProperties(user, ud);
            //获取粉丝数
            Map<String, Object> mapOne = new HashMap<>();
            mapOne.put("userid", user.getId());
            List<AppFollow> one = appFollowService.findByListAll(mapOne);
            ud.setFansnumall(one.size());
            //获取关注数
            Map<String, Object> mapTwo = new HashMap<>();
            mapTwo.put("followeduserid", user.getId());
            List<AppFollow> listOne = appFollowService.findByListAll(mapTwo);
            ud.setGuanzhu(listOne.size());
            //判断形象墙 是否存在
            if (!isNull(ud.getXingxiang())) {
                //形象墙存在 ,切割
                String[] arr = ud.getXingxiang().split(",");
                if (arr.length > 0) {
                    // /移入数组
                    ud.setXingxiangList(Arrays.asList(arr));
                }
            } else {
                //不存在  数组为空
                ud.setXingxiangList(Arrays.asList());
            }
            //判断用户是否登录
            if (isNull(request.getHeader(client_toke))) {
                ud.setGuanzhuState(2);
            } else {
                Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
                //获取当前登录用户的user对象
                AppUser appUser = appUserService.get(userId);
                //根据用户id和动态发布人userid查询是否已经关注
                AppFollow follow = appFollowService.getFollew(appUser.getId(), user.getId());
                if (!StringUtils.isEmpty(follow)) {
                    //已关注
                    ud.setGuanzhuState(1);
                } else {
                    //未查询到记录  未关注
                    ud.setGuanzhuState(2);
                }
            }
            //获取用户在房间的身份
            //判断用户是否和房间创建人是否是同一个人
            if (room.getUserid().equals(user.getId())) {
                //通过，房主
                ud.setRoomrole(room_role_fangzhu);
            } else {
                //不通过
                //判断用户是否是房间管理员
                AppRoomAdmin roomAdmin = appRoomAdminService.getRoom(room.getId(), user.getId());
                if (StringUtils.isEmpty(roomAdmin)) {
                    //未查询到记录, 用户身份
                    ud.setRoomrole(room_role_user);
                } else {
                    //查询到记录, 管理员身份
                    ud.setRoomrole(room_role_admin);
                }
            }
            //获取是否已经拉黑
            AppRoomLaHei appRoomLaHei = appRoomLaHeiService.getByRoomidAndUserid(room.getId(), user.getId());
            if (StringUtils.isEmpty(appRoomLaHei)) {
                ud.setIslahei(2);
            } else {
                //有记录   已啦黑
                ud.setIslahei(1);
            }
            //获取是否已经禁言
            AppRoomJinyan appRoomJinyan = appRoomJinyanService.getByRoomidAndUserid(room.getId(), user.getId());
            if (StringUtils.isEmpty(appRoomJinyan)) {
                ud.setIsjinyan(2);
            } else {
                //有记录   已禁言
                ud.setIsjinyan(1);
            }
            //贵族防T
            if (user.getIsguizu() == 1 && user.getNobleid() == 6) {
                ud.setKickOut(0);
            }

            return this.sucessJSON(ud);
        } catch (Exception e) {
            logger.error("查看某个用户的信息异常:", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }

    /**
     * @param userid 用户id
     * @param pageno 页码
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 查看某个用户的动态列表
     */
    @RequestMapping(value = "/getTdongtai")
    @ResponseBody
    public Result getTdongtai(HttpServletRequest request, Integer userid, Integer pageno) {
        try {
            if (isNull(userid)) {
                return errorJSON("userid不能为空");
            }
            if (pageno == null || pageno <= 0) {
                return this.errorJSON("没有更多数据了！");
            }
            //根据userid获取最新数据
            AppUser user = appUserService.getTcOrId(userid);
            //判断用户是否存在
            if (user == null || user.getId() == null || user.getId() <= 0) {
                return errorJSON("用户不存在");
            }
            //查询指定用户&正常的动态数据
            SplitPageBean splitPage = new SplitPageBean(pageno, 20);
            List<AppDynamic> dynamicList = appDynamicService.specificUserList(user.getId(), splitPage);
            List<DynamicDto> list = new ArrayList<>();
            //获取用户设置的头饰
            AppUserDressup userDressups = appUserDressupService.getUserid(user.getId(), 2);


            //判断数据是否为空
            if (dynamicList != null && dynamicList.size() > 0) {
                //遍历动态list
                for (AppDynamic appDynamic : dynamicList) {
                    //信息转移Dto
                    DynamicDto dd = new DynamicDto();
                    BeanUtils.copyProperties(appDynamic, dd);
                    if (!isNull(dd.getImage())) { //判断动态图片是否为空
                        String[] arr = dd.getImage().split(","); //不为空  切割
                        if (arr != null && arr.length > 0) {
                            dd.setImageList(Arrays.asList(arr)); //移入数组
                        }
                    } else {
                        dd.setImageList(Arrays.asList());//为空  数组则为空
                    }
                    //判断用户是否登录
                    Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
                    if (isNull(request.getHeader(client_toke)) || userId == null) {
                        //未登录  未点赞
                        dd.setDzstate(2);
                        dd.setGuanzhuState(2);
                    } else {
                        if (userId != null) {
                            AppUser appUser = appUserService.get(userId);
                            //根据用户id和动态id查询是否已经点赞
                            AppDynamicDianzan dianzan = appDynamicDianzanService.getSpecifiedLike(appUser.getId(), appDynamic.getId());
                            if (!StringUtils.isEmpty(dianzan)) {
                                dd.setDzstate(1);
                            } else {
                                dd.setDzstate(2);
                            }
                            //根据用户id和动态发布人userid查询是否已经关注
                            AppFollow follow = appFollowService.getFollew(appUser.getId(), appDynamic.getUserid());
                            if (!StringUtils.isEmpty(follow)) {
                                dd.setGuanzhuState(1);
                            } else {
                                dd.setGuanzhuState(2);
                            }
                        }
                    }
                    dd.setFabuTime(format(dd.getCreatetime()));

                    //判断是否设置过头饰
                    if (!StringUtils.isEmpty(userDressups)) {
                        //存在则放入
                        dd.setToushi(Constants.toushiCacheMap.get(userDressups.getMountsid()));
                    } else {
                        //不存在则表示未点赞
                        dd.setToushi("");
                    }
                    if (user.getIsguizu() == 1) {
                        //是贵族
                        //根据贵族id  获取贵族图标
                        String medal = guizuCacheMap.get(user.getNobleid());
                        dd.setMedal(medal);
                    } else {
                        dd.setMedal("");
                    }
                    //移入list
                    list.add(dd);
                }
                return this.sucessPage(list, splitPage.getNextPageNo());
            } else {
                return this.sucessPage(list, -1);
            }
        } catch (Exception e) {
            logger.error("查看某个用户的信息异常:", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * @param userid 用户id
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 查看某个用户的礼物墙
     */
    @RequestMapping(value = "/getTgiftQiang", method = RequestMethod.POST)
    @ResponseBody
    public Result getTgiftQiang(HttpServletRequest request, Integer userid) {
        try {
            if (isNull(userid)) {
                return errorJSON("userid不能为空");
            }
            //根据userid获取最新数据
            AppUser user = appUserService.getTcOrId(userid);
            //判断用户是否存在
            if (user == null || user.getId() == null || user.getId() <= 0) {
                return errorJSON("用户不存在");
            }
            //查询指定用户礼物墙
            List<AppUserGift> giftList = appUserGiftService.findList(user.getId());
            Map<String, Object> toMap = new HashMap<>(16);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            toMap.put("giftList", giftList);
            toMap.put("age", getAgeByBirth(user.getBirthday()));
            toMap.put("address", isNull(user.getAddress()) ? "" : user.getAddress());
            toMap.put("nianshouru", isNull(user.getNianshouru()) ? "" : user.getNianshouru());
            toMap.put("tizhong", isNull(user.getTizhong()) ? "" : user.getTizhong());
            toMap.put("shengao", isNull(user.getShengao()) ? "" : user.getShengao());
            toMap.put("zhiye", isNull(user.getZhiyename()) ? "" : user.getZhiyename());
            String phone = user.getLoginname().substring(0, 3) + "****" + user.getLoginname().substring(7, user.getLoginname().length());
            toMap.put("accountNumber", phone);
            List<String> bqList = new ArrayList<>();
            //判断用户是否添加标签
            if (!isNull(user.getBiaoqianname())) {
                //切割
                String[] bq = user.getBiaoqianname().split(",");
                bqList = Arrays.asList(bq);
            }
            toMap.put("biaoqian", bqList);
            toMap.put("xingzuo", getConstellation(formatter.format(user.getBirthday())));

            AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userid, ClientConstants.UserAuth.EDU_AUTH);
            if (appAuthUser != null && appAuthUser.getStatus() == 2) {
                toMap.put("xueli", appAuthUser.getField2());
            }
            return this.sucessJSON(toMap);
        } catch (Exception e) {
            logger.error("查看某个用户的信息异常:", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * 找回密码
     *
     * @Param: [loginname 手机号, code 验证码, password 密码]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/07/21
     */
    @RequestMapping("/zhaohui")
    @ResponseBody
    public Result zhaohuimima(String loginname, String code, String password) {
        try {
            if (StringEx.isNull(loginname)) {
                return this.errorJSON("手机号不能为空");
            }
            if (loginname.toLowerCase().contains("script")) {
                return this.errorJSON("请不要做非法攻击！");
            }
            if (StringEx.isNull(code)) {
                return this.errorJSON("验证码不能为空");
            }
            if (StringEx.isNull(password)) {
                return this.errorJSON("密码不能为空");
            }
            if (password.toLowerCase().contains("script")) {
                return this.errorJSON("请不要做非法攻击！");
            }
            if (code.toLowerCase().contains("script")) {
                return this.errorJSON("请不要做非法攻击！");
            }
            boolean exits = redisUtil.hasKey(RedisKeys.zcyzm + loginname);
            if (!exits) {
                return this.errorJSON("验证码不能为空！");
            }
            String values = redisUtil.get(RedisKeys.zcyzm + loginname).toString();
            if (StringEx.isNull(values)) {
                return this.errorJSON("验证码已过期，请重新获取验证码！");
            }
            if (!values.trim().equals(code)) {
                return this.errorJSON("验证码不正确，请重新输入！");
            }
            AppUser appUser = appUserService.findByUser(loginname, null);
            if (appUser == null) {
                return this.errorJSON("当前手机号未注册，请先注册");
            }
            //修改密码
            appUserService.upPassword(appUser.getId(), password);
            //删除验证码
            redisUtil.del(RedisKeys.zcyzm + loginname);
            return this.sucessJSON("保存成功");
        } catch (Exception e) {
            logger.error("找回密码异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    /**
     * 修改密码
     *
     * @Param: [password 旧密码, newpassword 新密码, surepassword 确认密码]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/07/21
     */
    @RequestMapping("/xiugai")
    @ResponseBody
    public Result xiugaimima(String password, String newpassword, String surepassword) {
        try {
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);

            if (StringEx.isNull(password)) {
                return this.errorJSON("原密码不能为空");
            }
            if (!appUser.getPassword().equals(password)) {
                return this.errorJSON("原密码输入错误，请重新输入");
            }
            if (StringEx.isNull(newpassword)) {
                return this.errorJSON("新密码不能为空");
            }
            if (StringEx.isNull(surepassword)) {
                return this.errorJSON("确认密码不能为空");
            }
            if (password.toLowerCase().contains("script")) {
                return this.errorJSON("请不要做非法攻击！");
            }
            if (newpassword.toLowerCase().contains("script")) {
                return this.errorJSON("请不要做非法攻击！");
            }
            if (surepassword.toLowerCase().contains("script")) {
                return this.errorJSON("请不要做非法攻击！");
            }
            if (!newpassword.equals(surepassword)) {
                return this.errorJSON("新密码与确认密码不同，请重新输入");
            }

            appUserService.upPassword(appUser.getId(), newpassword);
            return this.sucessJSON("修改成功");
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    /**
     * @Description 更新用户纬度
     * @Param: [lon经度, lat纬度 shi 市]
     */
    @RequestMapping("/updateWeiZhi")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result updateWeiZhi(String address, String addressdetail, String lon, String lat) {
        try {
            if (StringEx.isNull(lon)) {
                return this.errorJSON("经纬度不能为空");
            }
            if (StringEx.isNull(lat)) {
                return this.errorJSON("经纬度不能为空");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            appUserService.updateLonAndLat(userId, address, addressdetail, lon, lat);
            return this.sucessJSON("成功");
        } catch (Exception e) {
            logger.error("更新用户纬度异常", e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 获取年收入数组
     *
     * @return
     */
    @RequestMapping(value = "/getNianShouRu")
    @ResponseBody
    public Result getNianShouRu() {
        List<Object> list = new ArrayList<>();
        Map<Integer, String> map = ClientConstants.getNianShouRuMap();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            String mapValue = entry.getValue();
            Integer mapKey = entry.getKey();
            Map<String, Object> tomap = new HashMap<>(16);
            tomap.put("id", mapKey);
            tomap.put("value", mapValue);
            list.add(tomap);
        }
        return sucessJSON(list, "获取成功");
    }


    /**
     * 获取年收入数组
     *
     * @return
     */
    @RequestMapping(value = "/getXueLiRu")
    @ResponseBody
    public Result getXueLi() {
        List<Object> list = new ArrayList<>();
        Map<Integer, String> map = ClientConstants.getEduRuMap();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            String mapValue = entry.getValue();
            Integer mapKey = entry.getKey();
            Map<String, Object> tomap = new HashMap<>(16);
            tomap.put("id", mapKey);
            tomap.put("value", mapValue);
            list.add(tomap);
        }
        return sucessJSON(list, "获取成功");
    }


    /**
     * 获取身高数组
     *
     * @return
     */
    @RequestMapping(value = "/getShengao")
    @ResponseBody
    public Result getShengao() {
        List<Object> list = new ArrayList<>();
        Map<Integer, String> map = ClientConstants.getShenGaoMap();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            String mapValue = entry.getValue();
            Integer mapKey = entry.getKey();
            Map<String, Object> tomap = new HashMap<>(16);
            tomap.put("id", mapKey);
            tomap.put("value", mapValue);
            list.add(tomap);
        }
        return sucessJSON(list, "获取成功");
    }

    /**
     * 获取体重数组
     *
     * @return
     */
    @RequestMapping(value = "/getTizhong")
    @ResponseBody
    public Result getTizhong() {
        List<Object> list = new ArrayList<>();
        Map<Integer, String> map = ClientConstants.getTiZhongMap();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            String mapValue = entry.getValue();
            Integer mapKey = entry.getKey();
            Map<String, Object> tomap = new HashMap<>(16);
            tomap.put("id", mapKey);
            tomap.put("value", mapValue);
            list.add(tomap);
        }
        return sucessJSON(list, "获取成功");
    }

    /**
     * 获取职业数组
     *
     * @return
     */
    @RequestMapping(value = "/getZhiYe")
    @ResponseBody
    public Result getZhiYe() {
        List<AppZhiyeFu> fuList = appZhiyeFuService.list();
        for (AppZhiyeFu zhiyeFu : fuList) {
            List<AppZhiye> list = appZhiyeService.list(zhiyeFu.getCode());
            zhiyeFu.setZhiyeList(list);
        }
        return sucessJSON(fuList, "获取成功");
    }

    /**
     * 获取标签
     *
     * @return
     */
    @RequestMapping(value = "/getBiaoqian")
    @ResponseBody
    public Result getBiaoqian(@RequestParam(name = "country", defaultValue = "cn") String country) {
        //获取token
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser user = appUserService.get(userId);
        String[] arr = new String[100];
        if (!isNull(user.getBiaoqianid())) {
            arr = user.getBiaoqianid().split(",");
        }
        Map<String, Object> toMap = new HashMap<>(16);
        //获取个性标签
        List<AppBiaoqian> geList = appBiaoqianService.list(1, country);
        for (AppBiaoqian appBiaoqian : geList) {
            if (arr.length > 0) {
                boolean flag = Arrays.asList(arr).contains(appBiaoqian.getId() + "");
                if (flag) {
                    appBiaoqian.setIsselect(1);
                } else {
                    appBiaoqian.setIsselect(2);
                }
            } else {
                appBiaoqian.setIsselect(2);
            }
        }
        toMap.put("gexing", geList);
        //获取兴趣爱好
        List<AppBiaoqian> xingList = appBiaoqianService.list(2, country);
        for (AppBiaoqian appBiaoqian : xingList) {
            boolean flag = Arrays.asList(arr).contains(appBiaoqian.getId() + "");
            if (flag) {
                appBiaoqian.setIsselect(1);
            } else {
                appBiaoqian.setIsselect(2);
            }
        }
        toMap.put("xingqu", xingList);
        //获取直播标签
        List<AppBiaoqian> liveList = appBiaoqianService.list(3, country);
        toMap.put("liveLabel", liveList);
        return sucessJSON(toMap, "获取成功");
    }

    /**
     * 收费设置
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/priceSetting")
    @ResponseBody
    public Result priceSetting(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser user = appUserService.get(userId);
        if (user != null) {
            user.setPassword(null);

            Map<String, List<AppPriceSet>> priceListMap = priceSetService.typeList();

            AppSetup appSetup = appSetupService.get();

            map.put("user", user);
            map.put("priceList", priceListMap);
            map.put("explain", appSetup.getPriceSetExplain());
        }
        return this.sucessJSON(map);
    }

    /**
     * 保存消息价格设置
     *
     * @param type  1消息 2语音 3视频
     * @param price
     * @return
     */
    @RequestMapping(value = "/saveMessagePrice")
    @ResponseBody
    public Result saveMessagePrice(Integer type, String price) {
        Integer userId = getUserId();
        AppUser user = appUserService.get(userId);

        AppPriceSet appPriceSet = priceSetService.infoByTypeAndPrice(type, price);
        if (!price.equals("0")) {
            if (appPriceSet != null) {
                if (appPriceSet.getCharmLevel() == 1) {
                    if (user.getCharmvalue() == 0 || appPriceSet.getCharmLevelCondition().compareTo(Long.valueOf(user.getCharmvalue()).intValue()) > 0) {
                        return this.errorJSON("您的魅力值不够，无法设置这个单价。");
                    }
                }
            }
        }
        appUserService.saveMessagePrice(userId, type, price);
        return this.sucessJSON("成功");
    }

    /**
     * 修改消息开关状态
     *
     * @param type 1语音 2视频
     * @return
     */
    @RequestMapping(value = "/updateMessageStatus")
    @ResponseBody
    public Result updateMessageStatus(Integer type) {
        appUserService.updateMessageStatus(getUserId(), type);
        return this.sucessJSON("成功");
    }

    /**
     * 1谁看过我 2我看过谁
     *
     * @param request
     * @param pageno
     * @param type
     * @return
     */
    @RequestMapping(value = "/visitorLogPage")
    @ResponseBody
    public Result visitorLogPage(HttpServletRequest request, Integer pageno, Integer type) {
        Map<String, Object> map = new HashMap<>();
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);

        SplitPageBean splitPage = new SplitPageBean(pageno, 20);
        Map<String, Object> params = new HashMap<>();

        params.put("userId", userId);
        if (type == 1) {
            params.put("visitorType", "1");
        } else {
            params.put("visitorType", "2");
        }
        long l = System.currentTimeMillis();

        List<AppVisitor> list = visitorService.list(type, params, splitPage);

        long d = System.currentTimeMillis();
        DecimalFormat df = new DecimalFormat("0.000");
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + df.format((float) (d - l) / 1000) + "m");
        map.put("list", list);
        map.put("isvip", appUser.getVipEndDate() != null ? 1 : 0);
        return this.sucessPage(map, splitPage.getNextPageNo());
    }

    /**
     * 聊天前判断是否被拉黑
     *
     * @param tengxuncode
     * @return
     */
    @RequestMapping(value = "/isBlack")
    @ResponseBody
    public Result isBlack(Integer tengxuncode) {
        Map<String, Object> data = new HashMap<>();
        AppUser tengxuncodeByUser = appUserService.getTengxuncodeByUser(tengxuncode);
        if (tengxuncodeByUser != null) {
            AppUserLaHei appUserLaHei = appUserLaHeiService.getByUseridAndLhUserid(getUserId(), tengxuncodeByUser.getId());
            AppUserLaHei appUserLaHei1 = appUserLaHeiService.getByUseridAndLhUserid(tengxuncodeByUser.getId(), getUserId());

            data.put("pic", tengxuncodeByUser.getPic());
            data.put("isBlack", 0);
            if (appUserLaHei != null || appUserLaHei1 != null) {
                data.put("isBlack", 1);
            }

            data.put("intimacy", BigDecimal.ZERO);
            AppGuard guaardByUserId = appGuardService.getGuaardByUserId(getUserId(), tengxuncodeByUser.getId());
            if (guaardByUserId != null) {
                data.put("intimacy", guaardByUserId.getIntimacy());//获取亲密度、
            }

            AppSetup setup = appSetupService.get();
            data.put("intimacyvoice", setup.getIntimacyvoice());//获取亲密度、   '亲密度达到多少可以语音视频通话',
            data.put("free", 0);
            data.put("intimacyZuanshi", setup.getIntimacyZuanshi());//'亲密度兑换钻石比例，如1钻石=0.1亲密度',

            boolean eachGuild = appGuardService.isEachGuild(getUserId(), tengxuncodeByUser.getId());//是否是相互的守护
            if (eachGuild && guaardByUserId.getIntimacy().compareTo(new BigDecimal(Double.valueOf(setup.getIntimacyfreevoice()).toString())) > 0) {
                data.put("free", 1);
            }
        }
        return this.sucessJSON(data);
    }

    /**
     * 语音视频前判断是否拉黑、余额是否足够
     *
     * @param tengxuncode
     * @param type        1语音 2视频
     * @return
     */
    @RequestMapping(value = "/isEnoughVideoAndVoice")
    @ResponseBody
    public Result isEnoughVideoAndVoice(Integer tengxuncode, Integer type) {
        Map<String, Object> data = new HashMap<>();
        AppUser user = appUserService.get(getUserId());
        AppUser tengxuncodeByUser = appUserService.getTengxuncodeByUser(tengxuncode);
        AppUserLaHei appUserLaHei = appUserLaHeiService.getByUseridAndLhUserid(getUserId(), tengxuncodeByUser.getId());
        AppUserLaHei appUserLaHei1 = appUserLaHeiService.getByUseridAndLhUserid(tengxuncodeByUser.getId(), getUserId());

        data.put("pic", tengxuncodeByUser.getPic());
        data.put("isBlack", 0);
        if (appUserLaHei != null || appUserLaHei1 != null) {
            data.put("isBlack", 1);
        }

        data.put("intimacy", BigDecimal.ZERO);
        AppGuard guaardByUserId = appGuardService.getGuaardByUserId(getUserId(), tengxuncodeByUser.getId());
        if (guaardByUserId != null) {
            data.put("intimacy", guaardByUserId.getIntimacy());
        }

        AppSetup setup = appSetupService.get();
        data.put("intimacyvoice", setup.getIntimacyvoice());
        data.put("free", 0);
        data.put("intimacyZuanshi", setup.getIntimacyZuanshi());

        boolean eachGuild = appGuardService.isEachGuild(getUserId(), tengxuncodeByUser.getId());
        if (eachGuild && guaardByUserId.getIntimacy().compareTo(new BigDecimal(Double.valueOf(setup.getIntimacyfreevoice()).toString())) > 0) {
            data.put("free", 1);
        }

        //判断余额是否足够语音视频
        if (type == 1) {
            data.put("isEnoughVoice", 1);
            BigDecimal voicePrice = new BigDecimal(tengxuncodeByUser.getVoicePrice());
            if (!appUserService.isEnough(getUserId(), voicePrice)) {
                data.put("isEnoughVoice", 0);
//                TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), tengxuncode, "开通贵族：免费文字畅聊等特权~");
            }
        } else if (type == 2) {
            data.put("isEnoughVideo", 1);
            BigDecimal videoPrice = new BigDecimal(tengxuncodeByUser.getVideoPrice());
            if (!appUserService.isEnough(getUserId(), videoPrice)) {
                data.put("isEnoughVideo", 0);
//                TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), tengxuncode, "开通贵族：免费文字畅聊等特权~");
            }
        }

        return this.sucessJSON(data);
    }

    /**
     * 聊天扣费
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/feeDeduction")
    @ResponseBody
    public Result deduction(Integer txCode, Integer type) {
        AppSetup appSetup = appSetupService.get();
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser user = appUserService.get(userId);
        AppUser toUser = appUserService.getByTxCode(txCode);

        BigDecimal getMoney = new BigDecimal("0");
        BigDecimal diamonds = new BigDecimal("0");
        String mark = "";
        if (type == 2) {
            if (!toUser.getVoicePrice().equals("0")) {
                mark = "语音消息";
                diamonds = new BigDecimal(toUser.getVoicePrice());
                getMoney = new BigDecimal(toUser.getVoicePrice()).multiply(appSetup.getJinDouExchangeForDiamonds()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        } else if (type == 3) {
            if (!toUser.getVideoPrice().equals("0")) {
                mark = "视频消息";
                diamonds = new BigDecimal(toUser.getVideoPrice());
                getMoney = new BigDecimal(toUser.getVideoPrice()).multiply(appSetup.getJinDouExchangeForDiamonds()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        } else if (type == 4) {
            if (appSetup.getVoiceMatch() != 0) {
                mark = "语音速配";
                diamonds = new BigDecimal(appSetup.getVoiceMatch());
                getMoney = new BigDecimal(appSetup.getVoiceMatch()).multiply(appSetup.getJinDouExchangeForDiamonds()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        } else if (type == 5) {
            if (appSetup.getVideoMatch() != 0) {
                mark = "视频速配";
                diamonds = new BigDecimal(appSetup.getVideoMatch());
                getMoney = new BigDecimal(appSetup.getVideoMatch()).multiply(appSetup.getJinDouExchangeForDiamonds()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        }

        if (diamonds.compareTo(new BigDecimal("0")) > 0) {

            if (type != 4 && type != 5) {
                if (!appUserService.isEnough(userId, diamonds)) {
                    return this.errorJSON("钻石余额不足！");
                }
                doDeduction(type, diamonds, getMoney, userId, toUser.getId(), mark);
            } else {
                //男与女速配由男性扣费
                if (toUser.getSex() == 1) {
                    if (!appUserService.isEnough(toUser.getId(), diamonds)) {
                        return this.errorJSON("钻石余额不足！");
                    }
                    doDeduction(type, diamonds, getMoney, toUser.getId(), userId, mark);
                } else {
                    if (!appUserService.isEnough(userId, diamonds)) {
                        return this.errorJSON("钻石余额不足！");
                    }
                    doDeduction(type, diamonds, getMoney, userId, toUser.getId(), mark);
                }
            }

        } else {
            return this.errorJSON("被撩者没有设置语音/视频价格！");
        }

        return this.sucessJSON("成功");
    }

    @RequestMapping(value = "/tests")
    @ResponseBody
    public void tests() {
        JSONArray jsonArray = Constants.jsonArray;
        System.out.println(jsonArray);


    }


    /**
     * 文本消息扣费
     */
    @RequestMapping(value = "/textFeeDeduction")
    @ResponseBody
    public Result textFeeDeduction(Integer txCode, String text) {
        if (text == null) {
            return this.errorJSON("不能发空内容");
        }
        for (Object object : Constants.jsonArray) {
            if (text.contains(object.toString())) {
                System.out.println("内容包含敏感词：" + object);
                return this.errorJSON("内容不能包含敏感词");
            }
        }
        Integer userId = getUserId();
        AppUser user = appUserService.get(userId); //自己
        AppUser toUser = appUserService.getByTxCode(txCode); //对方
        if (ObjectUtil.isNull(user)) {
            return errorJSON("请先登录");
        }
        if (ObjectUtil.equal(2, user.getWindowTicket())) {
            return errorJSON("没用买门票");
        }
        if (ObjectUtil.equal(2, user.getStates())) {
            return errorJSON("账号已禁用");
        }
        if (ObjectUtil.isNull(toUser)) {
            return errorJSON("找不到好友！");
        }
        //vip:直接成功
        if(appUserService.isVip(userId)){
            return this.sucessJSON("成功");
        }

        String messagePrice = "6";
        BigDecimal diamonds = new BigDecimal(messagePrice);
        if (!appUserService.isEnough(user.getId(), diamonds)) {
            return this.errorJSON("钻石余额不足！");
        }

        //扣钻石, 加金币
        AppSetup appSetup = appSetupService.get();
        BigDecimal jinbi = new BigDecimal(messagePrice).multiply(appSetup.getJinDouExchangeForDiamonds()).setScale(2, BigDecimal.ROUND_HALF_UP);
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                doDeductionDelay(diamonds, jinbi, userId, toUser.getId(), "文本消息");
            }
        }).start();
        return this.sucessJSON("成功");
    }




//
//    /**
//     * 文本消息扣费
//     *
//     * @param txCode
//     * @return
//     */
//    @RequestMapping(value = "/textFeeDeduction")
//    @ResponseBody
//    public Result textFeeDeduction(Integer txCode, String text) {
//        //String text
//        Integer userId = getUserId();
//        if (userId == null) {//ttyb  04-23
//            return errorJSON("请先登录！");
//        }
//        if (text == null) {
//            return this.errorJSON("不能发空内容");
//        }
////        if (sensitiveWordDetection(text, Constants.keyWordSet)) {//ttyb  04-23
////            return this.errorJSON("内容不能包含敏感词aaa");
////        }
////        for (String e : Constants.keyWordSet) {
////            if (text.indexOf(e) > -1) {
////                return this.errorJSON("内容不能包含敏感词BBB");
////            }
////        }
////        System.out.println("开始" + System.currentTimeMillis());
//        for (Object object : Constants.jsonArray) {
//            if (text.contains(object.toString())) {
//                System.out.println("结束" + System.currentTimeMillis());
//                return this.errorJSON("内容不能包含敏感词BBB");
//
//            }
//        }
//        AppUser user = appUserService.get(userId); //自己
//        AppUser toUser = appUserService.getByTxCode(txCode); //对方
//        AppSetup appSetup = appSetupService.get();
//        Boolean isLovelyGod = false;
//        Boolean isHeart = false;
//
//        if (ObjectUtil.isNull(toUser)) {
//            return errorJSON("找不到好友！");
//        }
//        //如果聊天双方为异性
//        if ((user.getSex() == 1 && toUser.getSex() == 2) || (user.getSex() == 2 && toUser.getSex() == 1)) {
//            String key = "";
//            Integer manUserId = null, womanUserId = null;
//            AppUser manUser = new AppUser(), womanUser = new AppUser();
//            if (user.getSex() == 1 && toUser.getSex() == 2) {
//                manUserId = user.getId();
//                womanUserId = toUser.getId();
//
//                manUser = user;
//                womanUser = toUser;
//            } else if (user.getSex() == 2 && toUser.getSex() == 1) {
//                manUserId = toUser.getId();
//                womanUserId = user.getId();
//
//                manUser = toUser;
//                womanUser = user;
//            }
//
//            AppUser finalWomanUser = womanUser;
//            AppUser finalManUser = manUser;
//            //先判断是否为爱神牵线沟通
//            key = String.format(RedisKeys.LOVELY_GOD, manUserId, womanUserId);
//            if (redisUtil.hasKey(key)) {
//                isLovelyGod = true;
//                //先绑定聊天关系发起者，为男方发起
//                messageChatFromService.add(manUserId, womanUserId);
//
//                //女性回复牵线消息 赠送一个价值最低的礼物
//                AppGift lowMoneyGift = giftService.getLowMoneyGift();
//                appUserService.addJinbi(womanUserId, new BigDecimal(lowMoneyGift.getGoldmoney().toString()), "礼物收入");
//
//                new Thread(new Runnable() {
//                    @SneakyThrows
//                    @Override
//                    public void run() {
//                        Thread.sleep(3000);
//                        TxIm.sendUserGiftMsg(finalWomanUser.getTengxuncode(), finalManUser.getTengxuncode(), lowMoneyGift.getId(), lowMoneyGift.getGiftname(), lowMoneyGift.getGoldmoney().toString(), lowMoneyGift.getPicture(), lowMoneyGift.getSvgaaddress(), 2);
//                    }
//                }).start();
//                redisUtil.del(key);
//                return this.sucessJSON("成功");
//            }
//        }
//        String key1 = String.format(RedisKeys.BECKON_ALERT_ONE_TIP, user.getId(), toUser.getId());
//        String key1_b = String.format(RedisKeys.BECKON_ALERT_ONE_TIP, toUser.getId(), user.getId());
//        if (redisUtil.hasKey(key1) || redisUtil.hasKey(key1_b)) {
//            isHeart = true;
//            //如果不是爱神牵线消息，判断是否为心动后聊天
//            //四步都要判断 主动方发消息和被动方回复消息都要判断
//            //B回A男第二步
//            String key2 = String.format(RedisKeys.BECKON_ALERT_TWO_TIP, user.getId(), toUser.getId());
//            String key2_b = String.format(RedisKeys.BECKON_ALERT_TWO_TIP, toUser.getId(), user.getId());
//
//            String key3 = String.format(RedisKeys.BECKON_ALERT_THREE_TIP, user.getId(), toUser.getId());
//            String key3_b = String.format(RedisKeys.BECKON_ALERT_THREE_TIP, toUser.getId(), user.getId());
//
//            if (redisUtil.hasKey(key1) || redisUtil.hasKey(key1_b)) {
//                //如果当前为第一步，删除第一步缓存，设置第二步缓存
//                //第一步被动方回复消息
//                if (redisUtil.hasKey(key1_b)) {
//                    redisUtil.del(key1_b);
//                    key1 = String.format(RedisKeys.BECKON_ALERT_TWO_TIP, toUser.getId(), user.getId()); //当前是被动方回复消息 user当前是心动被动方 toUser当前是心动主动方
//                    redisUtil.set(key1, "1");
//
//                    /**
//                     * B回复A判断礼物key是否过期，未过期赠送礼物 增加账单 推送送礼消息
//                     * A发送三次心动礼物，B一次回复后全部收到
//                     */
//                    new Thread(new Runnable() {
//                        @SneakyThrows
//                        @Override
//                        public void run() {
//                            String giftKey = String.format(RedisKeys.BECKON_GIFT, toUser.getId(), user.getId());
//                            Set<String> giftKeys = redisUtil.keys(giftKey + "*");
//                            if (giftKeys != null && giftKeys.size() > 0) {
//                                for (String strKye : giftKeys) {
//                                    Integer giftId = Integer.valueOf(String.valueOf(redisUtil.get(strKye)));
//                                    redisUtil.del(strKye);
//
//                                    appGiftService.replyBeckoningGetGift(user.getId(), toUser.getId(), giftId);
//                                    AppGift gift = appGiftService.get(giftId);
//                                    TxIm.sendUserGiftMsg(user.getTengxuncode(), toUser.getTengxuncode(), gift.getId(), gift.getGiftname(), gift.getGoldmoney().toString(), gift.getPicture(), gift.getSvgaaddress(), 1);
//                                }
//                            }
//                        }
//                    }).start();
//                }
//            } else if (redisUtil.hasKey(key2) || redisUtil.hasKey(key2)) {
//                //如果当前为第二步，删除第二步缓存，设置第三步缓存 给B方发送对方和你聊天需要支付金币消息
//                //第二步主动方再次发送消息
//                if (redisUtil.hasKey(key2)) {
//                    redisUtil.del(key2);
//                    key2 = String.format(RedisKeys.BECKON_ALERT_THREE_TIP, user.getId(), toUser.getId());
//                    redisUtil.set(key2, "1");
//
//                    //给B方发送对方和你聊天需要支付金币消息
//                    new Thread(new Runnable() {
//                        @SneakyThrows
//                        @Override
//                        public void run() {
//                            Thread.sleep(3000);
//                            TxIm.sendUserMsgqbtAlert(toUser.getTengxuncode(), user.getTengxuncode(), "温馨提示：对方和你聊天会支付" + toUser.getMessagePrice() + "钻石/条，回复对方信息，" + toUser.getMessagePrice() + "元等值金币将赠送至您的账户，互相关注后，双方聊天免费。");
//                        }
//                    }).start();
//                }
//            } else if (redisUtil.hasKey(key3) || redisUtil.hasKey(key3_b)) {
//                //第三步被动方回复消息
//                //如果当前为第三步，删除第三步缓存，第四步提示女方获得金币
//                if (redisUtil.hasKey(key3_b)) {
//                    redisUtil.del(key3_b);
//
//                    new Thread(new Runnable() {
//                        @SneakyThrows
//                        @Override
//                        public void run() {
//                            Thread.sleep(3000);
//                            TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), toUser.getTengxuncode(), "【恭喜获得聊天奖励" + user.getMessagePrice() + "元。聊得越多，奖励越多~】");
//                        }
//                    }).start();
//                }
//            }
//        }
//
//        //互相关注发消息免费
//        boolean eachFollow = appFollowService.isEachFollow(userId, toUser.getId());
//        //
//        MessageChatFrom messageChatFrom = messageChatFromService.get(userId, toUser.getId());
//        if (!eachFollow) {
//            //文字消息扣费，查询聊天发起者，发起者扣费，被发起者收费//是否第一次发
//            if (messageChatFrom != null) {
//                //发起者发送消息扣费
//                MessageChatFrom from = messageChatFromService.getByFrom(userId, toUser.getId());
//                if (from != null) {
//                    AppUser toChatUser = appUserService.get(messageChatFrom.getToUserId());
//
//                    BigDecimal diamonds = new BigDecimal(toChatUser.getMessagePrice());
//                    if (diamonds.compareTo(BigDecimal.ZERO) > 0) {
//                        BigDecimal getMoney = new BigDecimal(toChatUser.getMessagePrice()).multiply(appSetup.getJinDouExchangeForDiamonds()).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        if (!appUserService.isEnough(messageChatFrom.getFromUserId(), diamonds)) {
////                            TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), toUser.getTengxuncode(), "开通贵族：免费文字畅聊等特权~");
//                            return this.errorJSON("钻石余额不足！");
//                        }
//                        new Thread(new Runnable() {
//                            @SneakyThrows
//                            @Override
//                            public void run() {
//                                doDeductionDelay(diamonds, getMoney, messageChatFrom.getFromUserId(), messageChatFrom.getToUserId(), "文本消息");
//                            }
//                        }).start();
//                    }
//                } else {
//                    new Thread(new Runnable() {
//                        @SneakyThrows
//                        @Override
//                        public void run() {
//                            //被发起者回复消息领取金币
//                            MessageChatFrom to = messageChatFromService.getByFrom(toUser.getId(), userId);
//                            if (to != null) {
//                                getDeduction(userId, toUser.getId());
//                            }
//                        }
//                    }).start();
//                }
//            } else {
//                AppUser toChatUser = appUserService.get(toUser.getId());
//                BigDecimal diamonds = new BigDecimal(toChatUser.getMessagePrice());
//                if (diamonds.compareTo(BigDecimal.ZERO) > 0) {
//                    BigDecimal getMoney = new BigDecimal(toChatUser.getMessagePrice()).multiply(appSetup.getJinDouExchangeForDiamonds()).setScale(2, BigDecimal.ROUND_HALF_UP);
//
//                    if (!appUserService.isEnough(userId, diamonds)) {
////                        TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), toUser.getTengxuncode(), "开通贵族：免费文字畅聊等特权~");
//                        return this.errorJSON("钻石余额不足！");
//                    }
//
//                    Boolean finalIsLovelyGod = isLovelyGod;
//                    Boolean finalIsHeart = isHeart;
//                    new Thread(new Runnable() {
//                        @SneakyThrows
//                        @Override
//                        public void run() {
//                            //如果不是爱神牵线聊天并且不是心动后聊天 给聊天被发起方发送对方和你聊天需要支付钻石通知
//                            if (!finalIsLovelyGod && !finalIsHeart) {
//                                TxIm.sendUserMsgqbtAlert(toUser.getTengxuncode(), user.getTengxuncode(), "为表诚意，对方和你聊天会支付" + diamonds + "钻石/条，回复对方，" + getMoney + "元等值金币将赠送至你的账户，互相关注后发对方消息免费，祝遇有缘人。");
//                            }
//                            messageChatFromService.add(userId, toUser.getId());
//                            doDeductionDelay(diamonds, getMoney, userId, toUser.getId(), "文本消息");
//                        }
//                    }).start();
//                }
//            }
//        }
//        return this.sucessJSON("成功");
//    }

    /**
     * 减少我的钻石 增加对方金币
     *
     * @param subZuanshi
     * @param addJinbi
     * @param fromUserId
     * @param toUserId
     */
    public void doDeduction(Integer type, BigDecimal subZuanshi, BigDecimal addJinbi, Integer fromUserId, Integer toUserId, String mark) {

        appUserService.upJianZuanShi(fromUserId, subZuanshi);
        appUserService.updatejinbi(toUserId, addJinbi);

        //我的钻石账单
        AppUser fromUser = appUserService.get(fromUserId);
        AppMingXiZuanShi zuanShi = new AppMingXiZuanShi();
        zuanShi.setUserid(fromUserId);
        zuanShi.setPic(fromUser.getPic());
        zuanShi.setPhone(fromUser.getLoginname());
        zuanShi.setNick(fromUser.getNick());
        zuanShi.setLeixing(2);
        zuanShi.setNum(subZuanshi);
        zuanShi.setCreatetime(new Date());
        zuanShi.setBeizhu(mark + "扣费");
        mingXiZuanShiService.saveOrUpdate(zuanShi);

        //对方金币账单
        AppUser toUser = appUserService.get(toUserId);
        AppMingxiJinbi jinbi = new AppMingxiJinbi();
        jinbi.setUserid(toUserId);
        jinbi.setPic(toUser.getPic());
        jinbi.setPhone(toUser.getLoginname());
        jinbi.setNick(toUser.getNick());
        jinbi.setLeixing(1);
        jinbi.setNum(addJinbi);
        jinbi.setCreatetime(new Date());
        jinbi.setBeizhu(mark + "收入");
        mingxiJinbiService.save(jinbi);

        Integer getCharm = 0;
        AppSetup appSetup = appSetupService.get();
        if (type == 1) {
            getCharm = appSetup.getEachMessageCharmGrowth();

        } else {
            getCharm = appSetup.getVoiceAndVideoEveryMinuteCharmGrowth();
        }

        appUserService.addCharm(toUserId, getCharm, "聊天");

        AppSetup setup = appSetupService.get();
        /*************************增加亲密度开始*******************/
        AppIntimacyGuard appIntimacyGuard = new AppIntimacyGuard();
        BigDecimal intimacy = subZuanshi.multiply(setup.getIntimacyZuanshi());
        appIntimacyGuard.setUserId(fromUserId);
        appIntimacyGuard.setBeiUserId(toUserId);
        appIntimacyGuard.setIntimacy(intimacy);
        appIntimacyGuard.setGiftMoney(addJinbi);
        appIntimacyGuard.setCreatetime(new Date());
        appIntimacyGuardService.addOrSaveIntimacyGuard(appIntimacyGuard);
        /*************************增加亲密度结束*******************/

        if (type == 2) {
            if (fromUser.getSex() != toUser.getSex()) {
                appDailyTasController.getAwardEveryDay(fromUserId, ClientConstants.TaskEveryDay.VOICE_CHAT);
            }
        } else if (type == 3) {
            if (fromUser.getSex() != toUser.getSex()) {
                appDailyTasController.getAwardEveryDay(fromUserId, ClientConstants.TaskEveryDay.VIDEO_CHAT);
            }
        }
    }

    /**
     * 聊天金币延时到账
     * A给B发的消息
     *
     * @param subZuanshi
     * @param addJinbi
     * @param fromUserId
     * @param toUserId
     * @param mark
     */
    public void doDeductionDelay(BigDecimal subZuanshi, BigDecimal addJinbi, Integer fromUserId, Integer toUserId, String mark) {
        appUserService.upJianZuanShi(fromUserId, subZuanshi);
        try{
            String key = String.format(RedisKeys.MESSAGE_CHAT_DEDUCTION, fromUserId, toUserId);// "MESSAGE_CHAT_DEDUCTION:%s:%s";
            Set<String> keys = redisUtil.keys(key + "*");
            if (keys != null && keys.size() > 0) {
                int size = keys.size();
                redisUtil.set(key + "_" + (size + 1), subZuanshi + "-" + addJinbi, Constants.RedisKeysLife.hours_12);
                redisUtil.set("COPY_" + key + "_" + (size + 1), subZuanshi + "-" + addJinbi, Constants.RedisKeysLife.hours_13);
            } else {
                redisUtil.set(key + "_" + 1, subZuanshi + "-" + addJinbi, Constants.RedisKeysLife.hours_12);
                redisUtil.set("COPY_" + key + "_" + 1, subZuanshi + "-" + addJinbi, Constants.RedisKeysLife.hours_13);
            }

            //我的钻石账单
            AppUser fromUser = appUserService.get(fromUserId);
            AppMingXiZuanShi zuanShi = new AppMingXiZuanShi();
            zuanShi.setUserid(fromUserId);
            zuanShi.setPic(fromUser.getPic());
            zuanShi.setPhone(fromUser.getLoginname());
            zuanShi.setNick(fromUser.getNick());
            zuanShi.setLeixing(2);
            zuanShi.setNum(subZuanshi);
            zuanShi.setCreatetime(new Date());
            zuanShi.setBeizhu(mark + "扣费");
            mingXiZuanShiService.saveOrUpdate(zuanShi);

            AppUser toUser = appUserService.get(toUserId);
            if (fromUser.getSex() != toUser.getSex()) {
                appDailyTasController.getAwardEveryDay(fromUserId, ClientConstants.TaskEveryDay.MESSAGE_CHAT);
            }
        }catch (Exception e){
        }
    }

    //B回复A后获得金币
    public void getDeduction(Integer fromUserId, Integer toUserId) {
        String key = String.format(RedisKeys.MESSAGE_CHAT_DEDUCTION, toUserId, fromUserId);
        Set<String> keys = redisUtil.keys(key + "*");
        if (keys != null && keys.size() > 0) {
            int i = 0;
            String firstValue = null;

            for (String str : keys) {
                if (i == 0) {
                    firstValue = redisUtil.get(str).toString();
                    redisUtil.del(str);
                } else {
                    String value = redisUtil.get(str).toString();
                    redisUtil.del(str);

                    Integer integer = Integer.valueOf(org.apache.commons.lang3.StringUtils.substring(str, str.length() - 1));
                    integer = integer - 1;
                    String key1 = key + "_" + integer;
                    redisUtil.set(key1, value);
                }
                i++;
            }

            int indexOf = org.apache.commons.lang3.StringUtils.indexOf(firstValue, "-");
            BigDecimal diamond = new BigDecimal(org.apache.commons.lang3.StringUtils.substring(firstValue, 0, indexOf));
            BigDecimal gold = new BigDecimal(org.apache.commons.lang3.StringUtils.substring(firstValue, indexOf + 1));
            appUserService.updatejinbi(fromUserId, gold);

            //对方金币账单
            AppUser toUser = appUserService.get(fromUserId);
            AppMingxiJinbi jinbi = new AppMingxiJinbi();
            jinbi.setUserid(fromUserId);
            jinbi.setPic(toUser.getPic());
            jinbi.setPhone(toUser.getLoginname());
            jinbi.setNick(toUser.getNick());
            jinbi.setLeixing(1);
            jinbi.setNum(gold);
            jinbi.setCreatetime(new Date());
            jinbi.setBeizhu("文本消息收入");
            mingxiJinbiService.save(jinbi);

            Integer getCharm = 0;
            AppSetup appSetup = appSetupService.get();
            getCharm = appSetup.getEachMessageCharmGrowth();

            appUserService.addCharm(fromUserId, getCharm, "聊天");

            AppSetup setup = appSetupService.get();
            //增加亲密度开始
            AppIntimacyGuard appIntimacyGuard = new AppIntimacyGuard();
            BigDecimal intimacy = diamond.multiply(setup.getIntimacyZuanshi());
            appIntimacyGuard.setUserId(toUserId);
            appIntimacyGuard.setBeiUserId(fromUserId);
            appIntimacyGuard.setIntimacy(intimacy);
            appIntimacyGuard.setGiftMoney(gold);
            appIntimacyGuard.setCreatetime(new Date());
            appIntimacyGuardService.addOrSaveIntimacyGuard(appIntimacyGuard);
        }
    }

    @RequestMapping(value = "/diamondEnough")
    @ResponseBody
    public Result deduction(Integer type) {
        AppSetup setup = appSetupService.get();

        AppUser user = appUserService.get(getUserId());
        if (type == 1) {
            if (new BigDecimal(String.valueOf(user.getDiamonds())).compareTo(new BigDecimal(String.valueOf(setup.getVoiceMatch()))) < 0) {
                return this.errorJSON("钻石余额不足！");
            }
        } else if (type == 2) {
            if (new BigDecimal(String.valueOf(user.getDiamonds())).compareTo(new BigDecimal(String.valueOf(setup.getVideoMatch()))) < 0) {
                return this.errorJSON("钻石余额不足！");
            }
        }
        return this.sucessJSON("success");
    }

    /**
     * 语音签名点赞
     *
     * @param toUserId
     * @return
     */
    @RequestMapping(value = "/parseVoiceSignature")
    @ResponseBody
    public Result parseVoiceSignature(Integer toUserId) {
        if (appSignatureParseLogService.isParse(getUserId(), toUserId) > 0) {
            return this.errorJSON("你已经点赞过了！");
        }

        AppSignatureParseLog param = new AppSignatureParseLog();
        param.setParseUserId(getUserId());
        param.setUserId(toUserId);
        appSignatureParseLogService.save(param);

        AppSetup appSetup = appSetupService.get();
        appUserService.addCharm(toUserId, appSetup.getVoiceSignatureParseGrowth(), "语音签名被点赞");

        return this.sucessJSON("成功");
    }

    /**
     * 查询语音接口和视频接听状态
     *
     * @return
     */
    @RequestMapping(value = "/userChatStatus")
    @ResponseBody
    public Result userChatStatus(Integer toUserId) {
        Map<String, Object> data = new HashMap<>();
        AppUser user = appUserService.getTengxuncodeByUser(toUserId);
        data.put("voiceStatus", user.getVoiceStatus());
        data.put("videoStatus", user.getVideoStatus());
        return this.sucessJSON(data);
    }

    /**
     * 获取用户认证状态
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userAuthStatus")
    @ResponseBody
    public Result userAuthStatus(@RequestParam(value = "userId", required = false) Integer userId) {
        if (userId == null || userId == 0) {
            userId = getUserId();
        }
        List<UserAuthDto> userAuthDtoList = appAuthUserService.infoByUser(userId);

        return this.sucessJSON(userAuthDtoList);
    }

    @RequestMapping(value = "/invite1")
    @ResponseBody
    public Result invite1() {
        List<AppInvitationRecord> byYaoqingList = appInvitationRecordService.findByYaoqingList(getUserId());

        return this.sucessJSON(byYaoqingList);
    }

    @RequestMapping(value = "/invite2")
    @ResponseBody
    public Result invite2() {
        List<AppInvitationRecord> byYaoqingList = appInvitationRecordService.findByYaoqingList(getUserId());
        return this.sucessJSON(byYaoqingList);
    }

    @RequestMapping(value = "/invite3")
    @ResponseBody
    public Result invite3() {

        List<Invite3Dto> invite3Dtos = appInvitationRecordService.invite3();
        for (Invite3Dto d : invite3Dtos) {
            AppUser appUser = appUserService.get(d.getUserId());
            appUser.setPassword(null);
            d.setAppUser(appUser);
        }
        return this.sucessJSON(invite3Dtos);
    }


    /**
     * 获取同城速配配置信息
     *
     * @return
     */
    @RequestMapping("/getSameCitySetting")
    @ResponseBody
    public Result getSameCitySetting() {
        List<AppSetSameCity> list = appSetSameCityService.getList();
        AppSetup setup = appSetupService.get();
        AppSetSameCityDto appSetSameCityDto = new AppSetSameCityDto();
        appSetSameCityDto.setSettingList(list);
        appSetSameCityDto.setSameCityForDiamonds(setup.getSameCityForDiamonds());
        return this.sucessJSON(appSetSameCityDto);
    }


    /**
     * 同城速配
     *
     * @param matchNumId  匹配人数id
     * @param textContent 发送说话内容
     * @return
     */
    @ResponseBody
    @RequestMapping("/sameCityMatch")
    public Result sameCityMatch(Integer matchNumId, String textContent) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        if (StringUtils.isEmpty(appUser)) {
            return this.errorJSON("用户不存在");
        }
        if (textContent.length() > 50) {
            return this.errorJSON("输入内容不能超过50字");
        }
        AppSetSameCity byId = appSetSameCityService.findById(matchNumId);
        if (byId == null) {
            return this.errorJSON("参数错误");
        }
        AppSetup setup = appSetupService.get();
        if (setup.getSameCityForDiamonds().compareTo(BigDecimal.ZERO) <= 0) {
            return this.errorJSON("该功能暂未开启，敬请期待");
        }
        BigDecimal payDiamonds = setup.getSameCityForDiamonds().multiply(new BigDecimal(byId.getNum()));
        if (payDiamonds.compareTo(BigDecimal.ZERO) <= 0) {
            return this.errorJSON("参数错误");
        }
        if (appUser.getDiamonds().compareTo(payDiamonds) < 0) {
            return this.errorJSON("钻石余额不足");
        }
        if (appUser.getSex() == 1) {
            List<AppUser> appUsers = appUserService.sameCityMatch(appUser.getId(), 2, appUser.getShiid(), byId.getNum(), setup.getSameCityForDiamonds(), textContent);
            if (appUsers != null && appUsers.size() > 0) {
//                return this.sucessJSON(appUsers,"success");
                return this.sucessJSON("匹配成功");
            }
        } else if (appUser.getSex() == 2) {
            List<AppUser> appUsers = appUserService.sameCityMatch(appUser.getId(), 1, appUser.getShiid(), byId.getNum(), setup.getSameCityForDiamonds(), textContent);
            if (appUsers != null && appUsers.size() > 0) {
//                return this.sucessJSON(appUsers,"success");
                return this.sucessJSON("匹配成功");
            }
        } else {
            return this.errorJSON("未获取到用户性别");
        }
//        return this.errorJSON("匹配成功");
        return this.sucessJSON("匹配成功");
    }

    /*@ResponseBody
    @RequestMapping("/getrecord")*/
    public Result getrecord(Integer toA, Integer fromA, Integer minTime, Integer maxTime) {
        try {
            Map<String, Object> map = TxIm.adminGetroammsg123(toA, fromA, minTime, maxTime);
            return this.sucessJSON(map, "成功");
        } catch (Exception e) {
            logger.error("异常", e);
            return this.errorJSON("fail");
        }
    }

    @ResponseBody
    @RequestMapping("/openYoung")
    public Result openYoung(String pass) {
        Integer userId = getUserId();
        AppUser user = appUserService.get(userId);
        if (user.getYoungMode() != null && user.getYoungMode() == 1) {
            return this.errorJSON("当前已是青少年模式，请勿重复开通！");
        }
        appUserService.openYoung(userId, pass);

        return this.sucessJSON("成功");
    }

    @ResponseBody
    @RequestMapping("/closeYoung")
    public Result closeYoung(String pass) {
        Integer userId = getUserId();
        AppUser user = appUserService.get(userId);
        if (!user.getYoungModePass().equals(pass)) {
            return this.errorJSON("密码输入错误！");
        }
        appUserService.closeYoung(userId);

        PopupLog popupLog = popupLogService.findOne(userId, 1);

        if (popupLog == null) {
            PopupLog popupLog2 = new PopupLog();
            popupLog2.setUserId(userId);
            popupLog2.setType(1);
            popupLogService.save(popupLog2);
        }
        return this.sucessJSON("成功");
    }

    @ResponseBody
    @RequestMapping("/youngStatus")
    public Result youngStatus() {
        Map<String, Object> data = new HashMap<>();
        Integer userId = getUserId();
        AppUser user = appUserService.get(userId);

        data.put("youngMode", user.getYoungMode() == null ? 0 : user.getYoungMode());
        return this.sucessJSON(data);
    }

    @ResponseBody
    @RequestMapping("/getPopup")
    public Result getPopup() {
        Integer userId = getUserId();
        PopupLog popupLog = popupLogService.findOne(userId, 1);
        PopupLog popupLog1 = popupLogService.findOne(userId, 2);

        if (popupLog1 == null) {
            PopupLog popupLog2 = new PopupLog();
            popupLog2.setUserId(userId);
            popupLog2.setType(2);
            popupLogService.save(popupLog2);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("pop1", popupLog != null ? 0 : 1);
        data.put("pop2", popupLog1 != null ? 0 : 1);
        return this.sucessJSON(data);
    }

    @ResponseBody
    @RequestMapping("/zhiding")
    public Result zhiding(Integer tengxuncode, Integer totengxuncode) {
        Zhiding param = new Zhiding();
        param.setTengxuncode(tengxuncode);
        param.setTotengxuncode(totengxuncode);
        zhidingService.add(param);
        return this.sucessJSON(param);
    }

    @ResponseBody
    @RequestMapping("/zhiding/list")
    public Result zhidinglist(Integer tengxuncode) {
        List<Zhiding> zhidings = zhidingService.listByUserId(tengxuncode);
        return this.sucessJSON(zhidings);
    }

    @ResponseBody
    @RequestMapping("/zhiding/del")
    public Result zhidingdel(Integer tengxuncode, Integer totengxuncode) {
        zhidingService.del(tengxuncode, totengxuncode);
        return this.sucessJSON("success");
    }

    @ResponseBody
    @RequestMapping("/userSetting/get")
    public Result userSettingGet() {
        Integer userId = getUserId();
        Map<String, Object> stringObjectMap = appUserSettingService.get(userId);

        AppUserSetting setting = new AppUserSetting();
        setting.setId(Integer.valueOf(stringObjectMap.get("id").toString()));
        setting.setUserId(Integer.valueOf(stringObjectMap.get("userId").toString()));
        setting.setHiddenGuardMe(Integer.valueOf(stringObjectMap.get("hiddenGuardMe").toString()));
        setting.setHiddenMyGuard(Integer.valueOf(stringObjectMap.get("hiddenMyGuard").toString()));
        setting.setHiddenArea(Integer.valueOf(stringObjectMap.get("hiddenArea").toString()));
        setting.setHiddenRank(Integer.valueOf(stringObjectMap.get("hiddenRank").toString()));
        return this.sucessJSON(setting);
    }

    /**
     * 隐私设置
     * 1隐藏守护我的人 2隐藏我守护的人 5排行榜隐身
     *
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping("/userSetting/update")
    public Result userSettingUpdate(Integer type) {
        Integer userId = getUserId();
        Map<String, Object> stringObjectMap = appUserSettingService.get(userId);

        AppUserSetting setting = new AppUserSetting();
        setting.setId(Integer.valueOf(stringObjectMap.get("id").toString()));
        setting.setUserId(Integer.valueOf(stringObjectMap.get("userId").toString()));
        setting.setHiddenGuardMe(Integer.valueOf(stringObjectMap.get("hiddenGuardMe").toString()));
        setting.setHiddenMyGuard(Integer.valueOf(stringObjectMap.get("hiddenMyGuard").toString()));
        setting.setHiddenArea(Integer.valueOf(stringObjectMap.get("hiddenArea").toString()));
        setting.setHiddenRank(Integer.valueOf(stringObjectMap.get("hiddenRank").toString()));

        if (type == 1) {
            if (setting.getHiddenGuardMe() == 1) {
                setting.setHiddenGuardMe(0);
            } else {
                setting.setHiddenGuardMe(1);
            }
        } else if (type == 2) {
            if (setting.getHiddenMyGuard() == 1) {
                setting.setHiddenMyGuard(0);
            } else {
                setting.setHiddenMyGuard(1);
            }
        } else if (type == 5) {
            AppUser appUser = appUserService.get(userId);
            if (appUser.getIsguizu() == 2 && appUser.getNobleid() < 2) {
                return this.errorJSON("您还不是贵族或者未达到指定等级，无法使用此功能！");
            }
            if (setting.getHiddenRank() == 1) {
                setting.setHiddenRank(0);
            } else {
                setting.setHiddenRank(1);
            }
        }
        appUserSettingService.saveOrUpdate(setting);
        return this.sucessJSON(setting);
    }

    /**
     * 隐私设置 位置信息选择 1精确 2模糊 3关闭
     *
     * @param value
     * @return
     */
    @ResponseBody
    @RequestMapping("/userSetting/hiddenArea/update")
    public Result userSettingAreaUpdate(Integer value) {
        Integer userId = getUserId();
        Map<String, Object> stringObjectMap = appUserSettingService.get(userId);

        AppUserSetting setting = new AppUserSetting();
        setting.setId(Integer.valueOf(stringObjectMap.get("id").toString()));
        setting.setUserId(Integer.valueOf(stringObjectMap.get("userId").toString()));
        setting.setHiddenGuardMe(Integer.valueOf(stringObjectMap.get("hiddenGuardMe").toString()));
        setting.setHiddenMyGuard(Integer.valueOf(stringObjectMap.get("hiddenMyGuard").toString()));
        setting.setHiddenArea(Integer.valueOf(stringObjectMap.get("hiddenArea").toString()));
        setting.setHiddenRank(Integer.valueOf(stringObjectMap.get("hiddenRank").toString()));

        setting.setHiddenArea(value);
        appUserSettingService.saveOrUpdate(setting);
        return this.sucessJSON(setting);
    }

    @ResponseBody
    @RequestMapping("/test")
    public void test() {
        List<AppUser> userListWoman = appUserService.findUserListBySex(2);
        List<AppUser> userListMan = appUserService.findUserListBySex(1);

        List<Integer> woManCollect = new ArrayList<>();
        List<Integer> woManCollectCopy = userListWoman.stream().map(e -> e.getId()).collect(Collectors.toList());
        woManCollectCopy.addAll(woManCollect);

        Collections.shuffle(userListMan);
        //遍历所有男性用户 匹配未联系过的女性用户
        for (AppUser u : userListMan) {
            List<MessageChatFrom> chatUserList = messageChatFromService.getByUserId(u.getId());

            //移除已经联系过的用户
            List<Integer> toUserIdCollect = chatUserList.stream().filter(e -> e.getFromUserId() == u.getId()).map(e -> e.getToUserId()).collect(Collectors.toList());
            List<Integer> fromUserIdCollect = chatUserList.stream().filter(e -> e.getToUserId() == u.getId()).map(e -> e.getFromUserId()).collect(Collectors.toList());
            woManCollectCopy.removeAll(toUserIdCollect);
            woManCollectCopy.removeAll(fromUserIdCollect);

            //移除已经牵线过的女用户
            List<LovelyGodLog> lovelyGodLogs = lovelyGodLogService.listByManId(u.getId());
            List<Integer> collect = lovelyGodLogs.stream().map(e -> e.getWomanUserId()).collect(Collectors.toList());
            woManCollectCopy.removeAll(collect);

            //打乱顺序 取一个用户
            Collections.shuffle(woManCollectCopy);
            if (woManCollectCopy != null && woManCollectCopy.size() > 0) {
                List<Integer> qbtWoManList = woManCollectCopy.subList(0, 1);

                Integer userId = qbtWoManList.get(0);
                AppUser user = appUserService.get(userId);
                TxIm.sendUserMsgqbt(user.getTengxuncode(), u.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功~");
                TxIm.sendUserMsgqbt(u.getTengxuncode(), user.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功，给她发个消息吧~");

                TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), u.getTengxuncode(), "♥爱神牵线成功♥，给对方发送消息可领取系统红包和礼物哦，快来回复吧！");
                TxIm.sendUserMsgqbtAlert(u.getTengxuncode(), user.getTengxuncode(), "爱神牵线聊天由男生支付钻石，对方设置了消息收费" + user.getMessagePrice() + "钻石/条");
                lovelyGodLogService.add(u.getId(), userId);

                String key = String.format(RedisKeys.LOVELY_GOD, u.getId(), userId);
                redisUtil.set(key, "1", 43200);
            }
            break;
        }
    }

    /**
     * 获取用户免费心动倒计时
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/heart/countdown")
    public Result heartCountdown() {
        Integer userId = getUserId();

        Map<String, Object> data = new HashMap<>();

        data.put("heartMatchPop", 0);

        String key = String.format(RedisKeys.FREE_HEART_COUNT_DOWN, userId);
        String keyFree = String.format(RedisKeys.FREE_HEART, userId);

        AppUser appUser = appUserService.get(userId);
        if (appUser.getSex() == 2) {
            data.put("countdown", redisUtil.getExpire(key));
            data.put("heartMatchPop", redisUtil.hasKey(keyFree) ? 1 : 0);
        } else if (appUser.getSex() == 1) {
            data.put("countdown", 0);
            if (redisUtil.hasKey(keyFree)) {
                if (appUser.getDiamonds().compareTo(new BigDecimal("3")) >= 0) {
                    data.put("heartMatchPop", 1);
                }
            }
        }
        return sucessJSON(data);
    }

    /**
     * 心动匹配6个用户
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/heart/match")
    public Result heartMatch() {
        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> userMap = null;
        Integer userId = getUserId();
        AppUser appUser = appUserService.get(userId);
        int sex = 1;
        if (appUser.getSex() == 1) {
            sex = 2;
        } else if (appUser.getSex() == 2) {
            sex = 1;
        }

        String ignoreUserIds = "";
        List<MessageChatFrom> chatUserList = messageChatFromService.getByUserId(userId);
        List<Integer> toUserIdCollect = chatUserList.stream().filter(e -> e.getFromUserId().compareTo(userId) == 0).map(e -> e.getToUserId()).collect(Collectors.toList());
        List<Integer> fromUserIdCollect = chatUserList.stream().filter(e -> e.getToUserId().compareTo(userId) == 0).map(e -> e.getFromUserId()).collect(Collectors.toList());
        if (toUserIdCollect != null && toUserIdCollect.size() > 0) {
            ignoreUserIds = org.apache.commons.lang3.StringUtils.join(toUserIdCollect, ",");
        }
        if (StringUtils.isEmpty(ignoreUserIds) && fromUserIdCollect != null && fromUserIdCollect.size() > 0) {
            ignoreUserIds += org.apache.commons.lang3.StringUtils.join(fromUserIdCollect, ",");
        } else if (fromUserIdCollect != null && fromUserIdCollect.size() > 0) {
            ignoreUserIds += "," + org.apache.commons.lang3.StringUtils.join(fromUserIdCollect, ",");
        }
        int limit = 0;
        if (appUser.getSex() == 1) {
            if (appUser.getDiamonds().compareTo(new BigDecimal("3")) >= 0 && appUser.getDiamonds().compareTo(new BigDecimal("6")) < 0) {
                limit = 3;
            } else if (appUser.getDiamonds().compareTo(new BigDecimal("6")) >= 0) {
                limit = 6;
            }
        } else {
            limit = 6;
        }

        List<AppUser> userList = appUserService.findOnlineUserListBySex(sex, ignoreUserIds, limit);
        for (AppUser u : userList) {
            userMap = new HashMap<>();
            userMap.put("id", u.getId());
            userMap.put("sex", u.getSex());
            userMap.put("pic", u.getPic());
            userMap.put("nick", u.getNick());
            data.add(userMap);
        }
        return sucessJSON(data);
    }

    /**
     * 心动匹配打招呼语
     *
     * @param sex
     * @return
     */
    @ResponseBody
    @RequestMapping("/heart/words")
    public Result heartWords(Integer sex) {
        if (sex == 1) {
            return sucessJSON(heartSayHelloCacheNan);
        } else {
            return sucessJSON(heartSayHelloCacheNv);
        }
    }

    /**
     * 批量心动
     *
     * @param userIds
     * @return
     */
    @ResponseBody
    @RequestMapping("/heart/send")
    @RedisSynchronized(key = "#userIds", second = 5)
    public Result heartSend(String userIds, String word) {
        Map<String, Object> data = new HashMap<>();
        if (StringUtils.isEmpty(userIds)) {
            return errorJSON("请选择心动人！");
        }
        Integer userId = getUserId();
        AppUser appUser = appUserService.get(userId);

        String key = String.format(RedisKeys.FREE_HEART, userId);
        if (appUser.getSex() == 2 && !redisUtil.hasKey(key)) {
            return errorJSON("倒计时未结束，还不能发送心动消息！");
        }

        String[] split = userIds.split(",");
        if (appUser.getSex() == 2) {
            for (String str : split) {
                AppUser toUser = appUserService.get(Integer.valueOf(str));

                MessageChatFrom chatFrom = messageChatFromService.get(userId, Integer.valueOf(str));
                if (chatFrom == null) {
                    messageChatFromService.add(Integer.valueOf(str), userId);
                }
                TxIm.sendUserMsgNew(toUser.getTengxuncode(), appUser.getTengxuncode(), word, "TIMTextElem");
            }
        } else if (appUser.getSex() == 1) {
            AppGift gift = appGiftService.randomGift(appUser.getDiamonds());
            for (String strUserId : split) {
                AppUser toUser = appUserService.get(Integer.valueOf(strUserId));

                MessageChatFrom chatFrom = messageChatFromService.get(userId, Integer.valueOf(strUserId));
                if (chatFrom == null) {
                    messageChatFromService.add(userId, Integer.valueOf(strUserId));
                }

                //扣费和账单
                appUserService.upJianZuanShi(userId, new BigDecimal(gift.getGoldmoney().toString()));
                AppMingXiZuanShi zuanShi = new AppMingXiZuanShi();
                zuanShi.setUserid(userId);
                zuanShi.setPic(appUser.getPic());
                zuanShi.setPhone(appUser.getLoginname());
                zuanShi.setNick(appUser.getNick());
                zuanShi.setLeixing(2);
                zuanShi.setNum(new BigDecimal(gift.getGoldmoney().toString()));
                zuanShi.setCreatetime(new Date());
                zuanShi.setBeizhu("心动礼物赠送");
                mingXiZuanShiService.saveOrUpdate(zuanShi);

                //A对B心动 设置第一步
                String keys = String.format(RedisKeys.BECKON_ALERT_ONE_TIP, userId, Integer.valueOf(strUserId));
                redisUtil.set(keys, "1", Constants.RedisKeysLife.hours_12);

                /**
                 *  设置心动礼物消息
                 *  礼物id+心动记录id
                 *  在对方回复的时候赠送礼物 增加账单记录
                 *  对方超时未回复删除redis key
                 */
                String giftKey = String.format(RedisKeys.BECKON_GIFT, userId, Integer.valueOf(strUserId));
                Set<String> giftKeys = redisUtil.keys(giftKey + "*");
                if (giftKeys != null && giftKeys.size() > 0) {
                    int size = giftKeys.size();
                    redisUtil.set(giftKey + "_" + (size + 1), gift.getId(), Constants.RedisKeysLife.hours_12);
                } else {
                    redisUtil.set(giftKey + "_" + 1, gift.getId(), Constants.RedisKeysLife.hours_12);
                }

                String str = "";
                String str1 = "";
                if (appUser.getSex() == 1) {
                    str = "小哥哥";
                    str1 = "他";
                } else if (appUser.getSex() == 2) {
                    str = "小姐姐";
                    str1 = "她";
                }
                TxIm.sendUserMsgNew(toUser.getTengxuncode(), appUser.getTengxuncode(), word, "TIMTextElem");
                TxIm.sendUserMsgqbtAlert(toUser.getTengxuncode(), appUser.getTengxuncode(), "你的魅力吸引了对面的" + str + "，12小时内回复信息可获得" + str1 + "的神秘礼物哦~");
            }
        }

        key = String.format(RedisKeys.FREE_HEART, userId);
        redisUtil.del(key);
        //重新开始倒计时
        if (appUser.getSex() == 2) {
            key = String.format(RedisKeys.FREE_HEART_COUNT_DOWN, userId);
            redisUtil.set(key, userId, 60 * 1 * 30);
        }
        data.put("countdown", 60 * 1 * 30);
        return sucessJSON(data);
    }

    /**
     * 封号操作
     */
    @ResponseBody
    @RequestMapping("/updateUserState")
    public Result updateUserState(Integer userId, Integer state, Integer hour) {


        try {


            if (StringEx.isNull(userId)) {
                return this.errorJSON("未获取到相关用户信息");
            }
            if (StringEx.isNull(state)) {
                return this.errorJSON("状态不能为空");
            }

            AppUser appUser = appUserService.get(userId);
            if (ObjectUtil.isNotEmpty(appUser)) {
                if (appUser.getWhiteStatus().equals(1)) {
                    afterUserService.upstate(userId, state, hour);
                    String key = String.format(RedisKeys.USER, userId);
                    redisUtil.del(key);
                    String header = request.getHeader(client_toke);
                    redisUtil.del(RedisKeys.userToken + header);
                    return this.sucessJSON("操作成功");
                }
            }
            return this.sucessJSON("请勿发送铭感/违法/不良内容，账号已进入监管");
        } catch (Exception e) {
            logger.error("账号解禁操作异常", e);
            return this.errorJSON("系统繁忙");
        }


    }

    /**
     * 首页获取18个随机用户
     */
    @RequestMapping(value = "/getRandomUserList")
    @ResponseBody
    public Result getRandomUserList() {
        Integer userId = getUserId();
        AppUser appUser = appUserService.get(userId);
        try {
            //获取数据女号
            List<AppUser> userListWoman = null;
            if (ObjectUtil.isNotEmpty(appUser)) {

                if (appUser.getSex().equals(1)) {
                    userListWoman = appUserService.findUserListByShuJuAndSex(2);
                }


                if (appUser.getSex().equals(2)) {
                    userListWoman = appUserService.findUserListBySex(1);
                }


            }
            assert userListWoman != null;
            Collections.shuffle(userListWoman);
            return this.sucessJSON(userListWoman.subList(0, 18));
        } catch (Exception e) {
            return this.errorJSON("系统繁忙");
        }

    }

    /**
     * 一键搭讪
     */
    @RequestMapping(value = "/selectAccost")
    @ResponseBody
    public Result selectAccost(String userId) {
        Integer ownUserId = getUserId();
        AppUser ownAppUser = appUserService.get(ownUserId);
        try {
            List<String> userIdList = Arrays.asList(userId.split(","));

            if (ObjectUtil.isNotEmpty(userIdList)) {

                userIdList.forEach(e -> {

                    AppUser matchUser = appUserService.get(Integer.valueOf(e));

                    TxIm.sendUserMsgqbt(matchUser.getTengxuncode(), ownAppUser.getTengxuncode(), "你和他很有缘哦，搭讪成功~");
                    TxIm.sendUserMsgqbt(ownAppUser.getTengxuncode(), matchUser.getTengxuncode(), "你和他很有缘哦，搭讪成功，给她发个消息吧~");



                    TxIm.sendUserMsgqbtAlert(matchUser.getTengxuncode(), ownAppUser.getTengxuncode(), "♥搭讪成功♥，给对方发送消息可领取系统红包和礼物哦，快来回复吧！");
                    TxIm.sendUserMsgqbtAlert(ownAppUser.getTengxuncode(), matchUser.getTengxuncode(), "搭讪聊天由男生支付钻石，对方设置了消息收费" + matchUser.getMessagePrice() + "钻石/条");


                    TxIm.sendUserMsgqbt(matchUser.getTengxuncode(), ownAppUser.getTengxuncode(), "开通贵族|享文字免费畅聊");
                    TxIm.sendUserMsgqbt(ownAppUser.getTengxuncode(), matchUser.getTengxuncode(), "开通贵族|享文字免费畅聊");
                });

            }
            return this.sucessJSON("搭讪成功");
        } catch (Exception e) {
            return this.errorJSON("系统繁忙");
        }

    }


    /**
     * 腾讯code获取用户列表
     */
    @GetMapping(value = "/getUserListByTxcodes")
    @ResponseBody
    public Result getUserListByTxcode(String txcodes) {
        List<AppUser> list = appUserService.findUserListByTxcodes(txcodes);
        list.forEach(user -> {
            if (user.getVipEndDate() != null) {
                user.setVip(TimeUtils.afterNow(user.getVipEndDate())? 1: 0);
            }
        });
        return this.sucessJSON(list);

    }


}
